package com.enation.app.javashop.buyer.api.member;

import com.enation.app.javashop.core.base.context.Region;
import com.enation.app.javashop.core.base.context.RegionFormat;
import com.enation.app.javashop.core.client.trade.ShetuanClient;
import com.enation.app.javashop.core.geo.model.RegeoCode;
import com.enation.app.javashop.core.geo.model.TencentLocation;
import com.enation.app.javashop.core.geo.service.GaodeManager;
import com.enation.app.javashop.core.geo.service.TencentManager;
import com.enation.app.javashop.core.member.model.dos.*;
import com.enation.app.javashop.core.member.model.dto.NearLeaderDTO;
import com.enation.app.javashop.core.member.model.vo.LeaderVO;
import com.enation.app.javashop.core.member.service.LeaderFansManager;
import com.enation.app.javashop.core.member.service.LeaderManager;
import com.enation.app.javashop.core.member.service.MemberManager;
import com.enation.app.javashop.core.promotion.shetuan.model.vo.ShetuanOrderStatisticVO;
import com.enation.app.javashop.core.trade.order.model.dto.ShetuanOrderQueryParam;
import com.enation.app.javashop.core.trade.order.service.CheckoutParamManager;
import com.enation.app.javashop.framework.context.UserContext;
import com.enation.app.javashop.framework.database.Page;
import com.enation.app.javashop.framework.util.BeanUtil;
import com.enation.app.javashop.framework.util.DateUtil;
import groovy.util.logging.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.constraints.NotEmpty;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 团长管理升级到自提点管理  by 2020/08/08
 */
@RestController
@RequestMapping(value = "/members/leader")
@Api(description = "团长api")
@Slf4j
public class LeaderBuyerController {

    private final Log logger = LogFactory.getLog(this.getClass());

    @Autowired
    private MemberManager memberManager;
    @Autowired
    private LeaderManager leaderManager;
    @Autowired
    private LeaderFansManager leaderFansManager;
    @Autowired
    private GaodeManager gaodeManager;
    @Autowired
    private ShetuanClient shetuanClient;
    @Autowired
    private CheckoutParamManager checkoutParamManager;
    @Autowired
    private TencentManager tencentManager;


    @ApiOperation(value = "团长招募", response = Void.class)
    @PostMapping(value = "leader_enroll")
    public void leaderEnroll(LeaderVO leaderVO, @RegionFormat @RequestParam(value = "region", required = true) Region region){
        LeaderDO leaderDO = new LeaderDO();
        BeanUtil.copyProperties(leaderVO, leaderDO);

        Member member = memberManager.getModel(leaderDO.getMemberId());
        if(member == null){
            throw new RuntimeException("会员不存在");
        }

        LeaderDO existsLeader = leaderManager.getByMemberId(member.getMemberId());
        if(existsLeader != null && (existsLeader.getAuditStatus() == 1 || existsLeader.getAuditStatus() == 2)){
            throw new RuntimeException("你已经申请自提站点了");
        }

        member.setRealName(leaderVO.getLeaderName());
        member.setMidentity(leaderVO.getMidentity());
        memberManager.edit(member, member.getMemberId());

        leaderDO.setLeaderCode(String.valueOf(DateUtil.getDateline()));
        leaderDO.setOriginSiteName(leaderVO.getSiteName());
        leaderDO.setLeaderMobile(member.getMobile());
        leaderDO.setProvince(region.getProvince());
        leaderDO.setCity(region.getCity());
        leaderDO.setCounty(region.getCounty());
        leaderDO.setTown(region.getTown());
        leaderDO.setProvinceId(region.getProvinceId());
        leaderDO.setCityId(region.getCityId());
        leaderDO.setCountyId(region.getCountyId());
        leaderDO.setTownId(region.getTownId());
        leaderDO.setOpStatus(1);
        leaderDO.setSourceFrom(2);
        leaderDO.setAuditStatus(1); // 审核中
        leaderDO.setFacadePicUrl(member.getFace());
        leaderManager.addLeader(leaderDO);
    }


    /**
     * 查询附近的团长(只查询审核通过的)
     */
    @GetMapping("near_leaders")
    @ApiImplicitParams({@ApiImplicitParam(name = "page_no", value = "页码", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "page_size", value = "每页显示数量", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "lat", value = "纬度", required = true, dataType = "number", paramType = "query"),
            @ApiImplicitParam(name = "lng", value = "经度", required = true, dataType = "number", paramType = "query")
    })
    public Page<NearLeaderDTO>  getNearLeader(@RequestParam(value = "lat") @NotEmpty(message = "经纬度不能为空") Double lat ,
                                              @RequestParam(value = "lng" ) @NotEmpty(message = "经纬度不能为空") Double lng,
                                              @RequestParam(value = "page_size" ) @NotEmpty(message = "分页大小不能为空")  Integer pageSize,
                                              @RequestParam(value="page_no") @NotEmpty(message = "pageNo不能为空") Integer pageNo){
        Page<NearLeaderDTO> page =  leaderManager.nearLeaderList(pageNo,pageSize,lng,lat);
        return page;
    }


    @PostMapping("band")
    @ApiOperation("绑定客户与团长的关系")
    @ApiImplicitParams({@ApiImplicitParam(name = "uuid", value = "用户uuid", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "leader_id", value = "团长id", required = true, dataType = "int", paramType = "query")
    })
    public boolean bandRel( @RequestParam(value = "leader_id" ) @NotEmpty(message = "团长id不能为空") Integer leaderId){
        LeaderFansDO  leaderFansDO = new LeaderFansDO();
        Integer uid =UserContext.getBuyer().getUid();       //会员主键
        leaderFansDO.setBuyerId(uid);
        leaderFansDO.setLeaderId(leaderId);
        leaderFansManager.band(leaderFansDO);
        // 设置结算自提点
        checkoutParamManager.setSiteId(leaderId);
        return true;
    }


    @ApiOperation("获取最后绑定的团长")
    @GetMapping({"last_leader","lastLeader"})
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lat", value = "纬度", required = false, dataType = "number", paramType = "query"),
            @ApiImplicitParam(name = "lng", value = "经度", required = false, dataType = "number", paramType = "query")
    })
    public NearLeaderDTO  getLastLeader(@RequestParam(value = "lat") Double lat ,@RequestParam(value = "lng") Double lng){
        if (UserContext.getBuyer() == null) {
            return null;
        }
        // 查询已绑定团长自提点
        BuyerLastLeaderDO lastLeaderDO = this.leaderFansManager.getLastLeader(UserContext.getBuyer().getUid());

        NearLeaderDTO returnLeader = null;

        // 查询出此客户最后绑定的团长关系
        if (lastLeaderDO != null) {
            LeaderDO leaderDO = this.leaderManager.getById(lastLeaderDO.getLeaderId());
            if (leaderDO.getAuditStatus() != 2 || leaderDO.getStatus()!=1) {
                return null;
            }
            TencentLocation tencentLocation = tencentManager.parseLatLng(lng,lat);

            if(tencentLocation.getAddress().contains(leaderDO.getCity())){
                returnLeader = new NearLeaderDTO();
                BeanUtil.copyProperties(leaderDO, returnLeader);
            }
        }

        // 自提点不存在，返回最近的一个自提点
        //if (returnLeader == null) {
        //    returnLeader = this.leaderManager.getNearestLeader(lat, lng);
        //
        //    if (returnLeader != null) {
        //        returnLeader.setRecommend(1);
        //        //把推荐的团长进行绑定
        //        LeaderFansDO leaderFansDO = new LeaderFansDO();
        //        leaderFansDO.setBuyerId(UserContext.getBuyer().getUid());
        //        leaderFansDO.setLeaderId(returnLeader.getLeaderId());
        //        leaderFansManager.band(leaderFansDO);
        //    }
        //}

        return returnLeader;
    }


    /**
     * 查询团长的收益记录
     */
    @ApiOperation(value = "查询团长的收益记录", response = ShetuanOrderStatisticVO.class)
    @PostMapping("query_profit_list")
    @Deprecated
    public Map<String, Object> queryProfitList(@RequestBody ShetuanOrderQueryParam queryParam){

        // 修复时间戳问题
        Long endTime = queryParam.getEndTime();
        if(endTime != null){
            endTime = endTime + 86400;
            queryParam.setEndTime(endTime);
        }

        Page<ShetuanOrderStatisticVO> page = shetuanClient.statistic(queryParam);
        List<ShetuanOrderStatisticVO> dataList = page.getData();
        if(dataList != null && !dataList.isEmpty()){
            for (ShetuanOrderStatisticVO shetuanOrderStatisticVO : dataList) {
                shetuanOrderStatisticVO.show();
            }
        }
        // 查询团长收益合计
        queryParam.setPageNo(1);
        queryParam.setPageSize(100000);
        ShetuanOrderStatisticVO orderStatisticVO = shetuanClient.statisticAll(queryParam);
        orderStatisticVO.show();

        // 封装结果
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("statisticCount", orderStatisticVO);
        resultMap.put("statisticPageList", page);
        return resultMap;
    }


    /**
     * 查询团长的粉丝列表
     */
    @ApiOperation(value = "查询团长的粉丝列表", response = LeaderFansDO.class)
    @GetMapping("query_fans_list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "leader_id", value = "团长id", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "page_no", value = "页码", required = true, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "page_size", value = "分页大小", required = true, paramType = "query", dataType = "int"),

    })
    public Page<LeaderFansDO> queryFansList(@ApiIgnore Integer leaderId,
                                            @ApiIgnore Integer pageNo,@ApiIgnore Integer pageSize){
        return leaderFansManager.getListByLeaderId(leaderId, pageNo, pageSize);
    }

    @ApiOperation(value = "设置营业时间", response = Void.class)
    @PostMapping(value = "set-work-time")
    public void setWorkTime(String workTime){
        LeaderDO leaderDO = leaderManager.getByMemberId(UserContext.getBuyer().getUid());
        leaderDO.setWorkTime(workTime);
        leaderManager.edit(leaderDO, leaderDO.getLeaderId());
    }

    @PostMapping("changeLocation")
    @ApiOperation("修改用户定位地址")
    public boolean changeLocation( ){
        return true;
    }

    private boolean judgeDistrict(Double lng, Double lat, String compareCountry){
        //判断当前选择位置是否为最后对应团长的区县
        RegeoCode regeoCode =  this.gaodeManager.parseLatLng(lng,lat);
        if(regeoCode.getAddressComponent() != null){
            return regeoCode.getAddressComponent().getDistrict().equals(compareCountry);
        }else {
            return  false;
        }
    }


    /**
     * 用户没有绑定过团长，系统则自动帮找出最近的推荐团长
     */
    private NearLeaderDTO recommendLeader(Double lng,Double lat){
        Page<NearLeaderDTO> page = this.leaderManager.nearLeaderList(1,1,lng,lat);
        if(page!=null && page.getData()!=null && page.getData().size()>0){
            return page.getData().get(0);
        }else{
            return null;
        }
    }
}
